<!--
 * @Author: zhangfeng
 * @Date: 2023-12-28 14:30:42
 * @LastEditTime: 2024-01-09 15:45:01
 * @LastEditors: zhangfeng
 * @Description: 权限弹框
 * @FilePath: \manager\managersystem\src\views\role\module\Premission.vue
 * © 2023 张峰，All rights reserved.
-->
<template>
	<el-dialog v-model="dialogVisible" :title="tips" width="30%">
		<el-tree
			v-loading="loading"
			element-loading-text="玩命加载中..."
			ref="treeRef"
			:data="dataTree"
			:props="defaultProps"
			show-checkbox
			node-key="id"
			:default-checked-keys="premissionIdArray"
			:current-node-key="CurrentKey"
			:default-expand-all="true"
			@getCheckedKeys="getCheckedKeys"
			check-strictly
			@check="handleCheck"
		/>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false">Cancel</el-button>
				<el-button type="primary" @click="handleConfirm"> Confirm </el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { getMenus } from '../../../api/menus';
import { buildTree } from '../../../utils/utils';
import { premissionRole } from '../../../api/role';
import { globalInjectSymbol } from '../../../utils/symbolKey';
import { useRoles } from '../../../composables/useRoles';
const { getPremissionAll } = useRoles();
const { successOrError } = inject(globalInjectSymbol) || {};
const dialogVisible = ref(false);
const tips = ref('权限列表');
const CurrentKey: Ref<string | undefined> = ref('1');
const dataTree = ref([] as MenuItemTree[]);
const treeRef = ref(null);
const loading = ref(true);
const RoleData = ref({} as RoleTableData);
const defaultProps = {
	children: 'children',
	label: 'name',
};
const premissionIdArray = ref([]);

const SelectionObj: Ref<TreeSelection | null> = ref(null);

const handleOpen = async (row: RoleTableData) => {
	premissionIdArray.value = [];
	dataTree.value = [];
	loading.value = true;
	dialogVisible.value = true;
	const { result } = (await getPremissionAll(
		row.id
	)) as AxiosResponse<ResponseData>;
	premissionIdArray.value = result.premissionId;
	await getMenusAll();
	RoleData.value = row;
	loading.value = false;
};

const getMenusAll = async () => {
	const res: AxiosResponse<List> = await getMenus();
	dataTree.value = (await buildTree(res.result.list)) as MenuItemTree[];
};
const handleCheck = (nodeObj: MenuItemTree[], Selection: TreeSelection) => {
	console.log(nodeObj);
	console.log(Selection);
	SelectionObj.value = Selection;
};
const getCheckedKeys = (leafOnly: boolean) => {
	console.log(leafOnly);
};

const handleConfirm = async () => {
	const result: AxiosResponse<ResponseData> = await premissionRole({
		roleId: RoleData.value.id,
		premissionId: SelectionObj.value?.checkedKeys,
	});
	if (successOrError) {
		await successOrError(result);
		dialogVisible.value = false;
	}
};
defineExpose({
	handleOpen,
});
</script>

<style scoped></style>
